package com.timebank.auth.service;

import com.timebank.auth.constant.LoginTypeConstant;
import com.timebank.common.core.exception.captcha.CaptchaException;
import com.timebank.system.pojo.LoginDTO;
import com.timebank.system.pojo.SysUser;
import com.timebank.common.core.constant.CacheConstants;
import com.timebank.common.core.constant.Constants;
import com.timebank.common.core.constant.SecurityConstants;
import com.timebank.common.core.constant.UserConstants;
import com.timebank.common.core.enums.UserStatus;
import com.timebank.common.core.exception.ServiceException;
import com.timebank.common.core.result.Result;
import com.timebank.common.core.text.Convert;
import com.timebank.common.core.utils.StringUtils;
import com.timebank.common.core.utils.ip.IpUtils;
import com.timebank.common.redis.service.RedisService;
import com.timebank.common.security.utils.SecurityUtils;
import com.timebank.system.service.RemoteUserService;
import com.timebank.system.model.LoginUser;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 登录校验方法
 * 
 * @author shiliuyinzhen
 */
@Component
public class LoginService {

    @Resource
    private RemoteUserService remoteUserService;

    @Resource
    private PasswordService passwordService;

    @Resource
    private RecordLogService recordLogService;

    @Resource
    private RedisService redisService;

    /**
     * 用户登录
     * @param loginDTO
     * @return
     */
    public LoginUser login(LoginDTO loginDTO) {
        //获取登录类型
        Integer loginType = loginDTO.getLoginType();

        //获取用户名及密码
        String username =  loginDTO.getUsername();
        String password = loginDTO.getPassword();

        //获取邮箱和验证码
        String email = loginDTO.getEmail();
        String emailCode = loginDTO.getEmailCode();

        Result<LoginUser> userResult = new Result<>();

        //如果是用户名和密码登录
        if (loginType.equals(LoginTypeConstant.USERNAME_PASSWORD)){

            // 用户名或密码为空 错误
            if (StringUtils.isAnyBlank(username, password)) {
                recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
                throw new ServiceException("用户/密码必须填写");
            }
            // 密码如果不在指定范围内 错误
            if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                    || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
                recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
                throw new ServiceException("用户密码长度不在指定范围");
            }
            // 用户名不在指定范围内 错误
            if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                    || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
                recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
                throw new ServiceException("用户名长度不在指定范围");
            }
            // 查询用户信息
            userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);
            if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
                recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
                throw new ServiceException("登录用户：" + username + " 不存在");
            }
            if (Result.FAIL == userResult.getCode()) {
                throw new ServiceException(userResult.getMsg());
            }

        } else if (loginType.equals(LoginTypeConstant.EMAIL_PASSWORD)) {
            if (email == null || email == ""){
                throw new ServiceException("邮箱不能为空");
            }
            //如果是邮箱及密码登录
            //查询用户信息
            userResult = remoteUserService.getUserInfoByEmail(email,SecurityConstants.INNER);
            if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
                recordLogService.recordLogininfor(email, Constants.LOGIN_FAIL, "登录邮箱不存在");
                throw new ServiceException("登录邮箱：" + email + " 不存在");
            }
            if (Result.FAIL == userResult.getCode()) {
                throw new ServiceException(userResult.getMsg());
            }
        } else if (loginType.equals(LoginTypeConstant.EMAIL_CODE)){
            //如果是邮箱和验证码登录
            if (email == null || email == ""){
                throw new ServiceException("邮箱不能为空");
            }
            //校验验证码
            if (StringUtils.isEmpty(emailCode)) {
                throw new CaptchaException("验证码不能为空");
            }

            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + email;
            String captcha = redisService.getCacheObject(verifyKey);

            if (captcha == null || captcha == "") {
                throw new CaptchaException("验证码已失效");
            }
            if (!emailCode.equals(captcha)) {
                throw new CaptchaException("验证码错误");
            }
            //查询用户信息
            userResult = remoteUserService.getUserInfoByEmail(email,SecurityConstants.INNER);
            if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
                recordLogService.recordLogininfor(email, Constants.LOGIN_FAIL, "登录邮箱不存在");
                throw new ServiceException("登录邮箱：" + email + " 不存在");
            }
            if (Result.FAIL == userResult.getCode()) {
                throw new ServiceException(userResult.getMsg());
            }
            //删除缓存
            redisService.deleteObject(verifyKey);
        } else {
            throw new ServiceException("暂未处理");
        }

        LoginUser userInfo = userResult.getData();
        SysUser sysUser = userResult.getData().getSysUser();
        username = sysUser.getUserName();
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIp())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }

        if (UserStatus.DELETED.getCode().equals(sysUser.getDelFlag())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(sysUser.getStatus())) {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }

        //校验密码
        if (loginType.equals(LoginTypeConstant.USERNAME_PASSWORD)
                || loginType.equals(LoginTypeConstant.EMAIL_PASSWORD)
        ){
            passwordService.validate(sysUser, password);
        }

        //更新用户登录时间和ip
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        sysUser.setLoginIp(IpUtils.getIp());
        sysUser.setLoginTime(LocalDateTime.now());
        remoteUserService.updateUserLoginInfo(sysUser,SecurityConstants.INNER);
        return userInfo;
    }

    /**
     * 用户退出
     * @param loginName
     */
    public void logout(String loginName)
    {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 用户注册
     * @param sysUser
     * @return
     */
    public void register(SysUser sysUser) {

        String userName =  sysUser.getUserName();
        String nickName =  sysUser.getNickName();
        String password =  sysUser.getPassword();

        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(userName, password)) {
            throw new ServiceException("用户/密码必须填写");
        }
        if (StringUtils.isAnyBlank(nickName, password)) {
            throw new ServiceException("用户昵称必须填写");
        }
        if (userName.length() < UserConstants.USERNAME_MIN_LENGTH
                || userName.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new ServiceException("用户名长度必须在2到20个字符之间");
        }
        if (nickName.length() < UserConstants.USERNAME_MIN_LENGTH
                || nickName.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new ServiceException("昵称长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        sysUser.setUserName(userName);
        sysUser.setNickName(nickName);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        Result<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (Result.FAIL == registerResult.getCode()) {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(userName, Constants.REGISTER, "注册成功");
    }
}
